<template>
<div>
  <div
      style="width: 1670px;min-height:770px;padding:24px 32px;margin:15px 0 15px 35px;
        border-radius: 26px;background-color: white">
    <div v-if="!scoringShow">
      <p style="margin: 0;font-size: 18px">
        <el-form style="display: flex">
          <a style="margin-top: 6px">批改作业</a>
          <i class="el-icon-arrow-right" style="margin: 10px"></i>
          <el-form-item style="width: 150px">
            <el-select v-model="chapterId" placeholder="请选择章节">
              <el-option @click.native="onClickChapter()" v-for="(item,index) in chapterList"
                         :key="item.chapterId" :label="item.chapterName" :value="item.chapterId"></el-option>
            </el-select>
          </el-form-item>
          <i class="el-icon-arrow-right" style="margin: 10px"></i>
          <el-form-item style="width: 150px">
            <el-select v-model="taskId" placeholder="请选择作业">
              <el-option @click.native="onClickTask()" v-for="(item,index) in taskList"
                         v-if="item.chapterId===chapterId"
                         :key="item.taskId" :label="item.taskName" :value="item.taskId"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </p>
      <el-row>
        <div v-for="(item,index) in taskScoreList"
             style="margin: 20px 0 30px 30px" :id="'taskScore-'+index">
          <div style="display: flex;height: 32px">
            <el-link :href="'/#/learnEdit/testScoring/'+courseId+'/'+chapterId+'/'+item.taskId+'/'+item.userId"
                     style="font-size: 16px;" :underline="false">
              <div style="display: flex;height: 32px;width: 660px;padding-top: 8px">
                <a v-if="item.scoreFlag==='1'" class="el-icon-circle-check" style="border-radius: 50%;
                background-color: #409EFF;color: white;font-size: 24px;height: 24px;width: 24px"></a>
                <a v-else class="el-icon-remove-outline" style="font-size: 24px;"></a>
                <div style="margin: 4px 0 0 8px">用户 {{ item.userName }} | 提交于 {{item.updateTime|formatDate('yyyy-MM-dd HH:mm:ss')}} | 第 {{item.submitNum}} 次提交 </div>
              </div>
            </el-link>
          </div>
        </div>
      </el-row>
      <el-pagination
          @size-change="handleSizechange"
          @current-change="getPageTaskScore"
          :current-page="currentPage"
          :page-sizes="[10,15,20]"
          :page-size="pageSize"
          layout="total,sizes,prev,pager,next,jumper"
          :total="total"
          style="text-align: center">
      </el-pagination>
    </div>
    <div v-else>
      <el-form :model="taskScore" :rules="rules" label-width="30px" style="display: flex;flex-direction: column;width: 800px" ref="taskScoreForm">
        <h2 style="margin-top: 6px">批改作业</h2>
        <h3>{{task.taskName}}</h3>
        <h4 style="margin:0 0 0 30px;">学生姓名</h4>
        <div v-html="taskScore.userName" style="margin:0 0 30px 40px;">
        </div>
        <h4 style="margin:0 0 0 30px;">作业题目</h4>
        <div v-html="task.content" style="margin:0 0 30px 40px;">
        </div>
        <h4 style="margin:0 0 0 30px;">学生答案</h4>
        <div v-html="taskScore.content" style="margin:0 0 30px 40px;">
        </div>
        <h4 style="margin:0 0 0 30px;">参考答案</h4>
        <div v-html="task.answer" style="margin:0 0 30px 40px;">
        </div>
        <p style="font-size: 18px;margin-left: 30px">作业打分 总分：{{task.score}}</p>
        <el-form-item prop="score">
          <el-input-number v-model="taskScore.score" :precision="2" :step="0.1" :max="task.score"></el-input-number>
        </el-form-item>
        <p style="font-size: 18px;margin-left: 30px">评语</p>
        <el-form-item prop="scoreContent">
          <div id="div1">
          </div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="addOrUpdate('taskScoreForm')">提 交</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</div>
</template>

<script>
import E from 'wangeditor'
export default {
  name: "TestScoringView",
  data(){
    return{
      courseId: '',
      chapterId: '',
      taskId: '',
      userId:'',
      chapterList:'',
      scoringShow:false,
      task:{},
      taskList:'',
      taskScore:{scoreContent:''},
      taskScoreList:[],
      isChange:false,
      currentPage: 1,
      pageSize: 10,
      total: 10,
      rules:{
        score:{required: true, message: '分数不能为空', trigger: 'blur'}
      }
    }
  },
  watch:{
    taskScore(val){
      if(!this.isChange){
        this.editor.txt.html(this.taskScore.scoreContent);
      }
      this.isChange=false;
    }
  },
  methods: {
    getChapterByCourseId(courseId) {
      this.$axios({
        method: 'get',
        url: `http://localhost:8089/chapter/selectChapterByCourseId/${courseId}`
      }).then(res => {
        if (res.data.code === 200)
          this.chapterList = res.data.dataobject;
      }).catch(err => console.log(err));
    },
    getTaskByCourseId(courseId) {
      this.$axios({
        method: 'get',
        url: `http://localhost:8089/user/task/selectTaskByCourseId/${courseId}`
      }).then(res => {
        if (res.data.code === 200)
          this.taskList = res.data.dataobject;
      }).catch(err => console.log(err));
    },
    handleSizechange(size) {
      this.pageSize = size;
      this.getPageTaskScore(1);
    },
    getPageTaskScore(current = 1) {
      this.currentPage = current;
      this.$axios({
        method: 'get',
        url: `http://localhost:8089/taskscore/getPageScoreByTaskId/${this.currentPage}/${this.pageSize}/${this.taskId}`
      }).then(res => {
        if (res.data.code === 200) {
          this.total = res.data.dataobject.total;
          this.taskScoreList = res.data.dataobject.pageList;
        }
      }).catch(err => console.log(err));
    },
    getTaskByTaskId(taskId) {
      this.$axios({
        method: 'get',
        url: `http://localhost:8089/task/selectTaskById/${taskId}`
      }).then(res => {
        if (res.data.code === 200)
          this.task = res.data.dataobject;
      }).catch(err => console.log(err));
    },
    getTaskScoreByUserAndTask(taskId,userId){
      this.$axios({
        method: 'get',
        url: `http://localhost:8089/taskscore/selectTaskscoreByUserAndTask/${userId}/${taskId}`,
      }).then(res => {
        if (res.data.code === 200) {
          this.taskScore = res.data.dataobject;
        }
      }).catch(err => console.log(err));
    },

    //创建富文本编辑器，并进行上传图片、上传视颜的配置
    createRichTextEditor() {
      this.editor = new E('#div1');
      this.editor.config.uploadImgServer = 'http://localhost:8089/richText/uploadFile?type=img';
      this.editor.config.uploadFileName = 'file';
      this.editor.config.uploadVideoServer = 'http://localhost:8089/richText/uploadFile?type=video';
      this.editor.config.uploadVideoName = 'file';
      this.editor.config.placeholder = '请在此处作答';
      this.editor.config.zIndex=500
      this.editor.config.onchange = (html)=>{
        this.isChange = true;
        this.taskScore.scoreContent=html//绑定当前逐渐地值
      }
      this.editor.create();
    },
    TaskScoreScoring(){
      this.$axios({
        method: 'post',
        url: `http://localhost:8089/user/taskscore/TaskscoreScoring`,
        data:this.taskScore
      }).then(res => {
        if (res.data.code === 200) {
          this.$message.success(res.data.msg)
        }else {
          this.$message.error(res.data.msg)
        }
      }).catch(err => console.log(err));
    },
    //提交按钮
    addOrUpdate(formName) {
      this.taskScore.scoreContent=this.editor.txt.html();
      this.$refs[formName].validate((valid) => {
        if (valid) {
            this.TaskScoreScoring()
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    onClickChapter() {
      this.taskId = '';
    },
    onClickTask() {
      this.$router.push({
        path: '/learnEdit/testScoring/' + this.courseId + '/' + this.chapterId + '/' + this.taskId
      }).catch(err => console.log(err));
    },
  },
  filters:{
    formatDate: function(value,args) {
      var dt = new Date(value);
      if(args == 'yyyy年MM月dd日') {// yyyy年MM月dd日
        let year = dt.getFullYear();
        let month = (dt.getMonth() + 1).toString().padStart(2,'0');
        let date = dt.getDate().toString().padStart(2,'0');
        return `${year}年${month}月${date}日`;
      } else if(args == 'yyyy-MM-dd HH:mm:ss'){// yyyy-MM-dd HH:mm:ss
        let year = dt.getFullYear();
        let month = (dt.getMonth() + 1).toString().padStart(2,'0');
        let date = dt.getDate().toString().padStart(2,'0');
        let hour = dt.getHours().toString().padStart(2,'0');
        let minute = dt.getMinutes().toString().padStart(2,'0');
        let second = dt.getSeconds().toString().padStart(2,'0');
        return `${year}-${month}-${date} ${hour}:${minute}:${second}`;
      }
    }
  },
  created(){
    this.courseId = parseInt(this.$route.params.courseId);
    this.chapterId = parseInt(this.$route.params.chapterId);
    this.taskId = parseInt(this.$route.params.taskId);
    if(this.$route.params.userId){
      this.userId=this.$route.params.userId
      this.scoringShow=true
      this.getTaskByTaskId(this.taskId)
      this.taskscore={scoreContent:''}
      this.getTaskScoreByUserAndTask(this.taskId,this.userId)
      this.$nextTick(() => {
        if (!this.editor) {
          this.createRichTextEditor();
        }
      });
    }
    this.getChapterByCourseId(this.courseId)
    this.getTaskByCourseId(this.courseId)
    this.getPageTaskScore()
  }
}
</script>

<style scoped>

</style>